﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ElFinder.Connector.Utils;
namespace ElFinder.Connector.Commands
{
    public class Tmb : ICommand
    {
        public string Current { get; set; }

        public Tmb(string current)
        {            
            this.Current = current;            
        }

        #region ICommand Members       

        public ElFinder.Connector.Responses.Response Execute()
        {
            var path = DirectoryUtils.GetRelativePathByHash(Current);

            var response = new Responses.ThumbnailResponse();

            response.current = Current;

            response.tmb = false;

            var images = new List<string>();

            var imageFormatString = @"'{0}' : '{1}'";

            var directoryInfo = new System.IO.DirectoryInfo(path);

            var patterns = "*.jpg,*.jpeg,*.png,*.gif,*.bmp".Split(",".ToCharArray());

            List<System.IO.FileInfo> files = new List<System.IO.FileInfo>();
            foreach (var pattern in patterns)
            {
                files.AddRange(directoryInfo.GetFiles(pattern));
            }

            var filesCount = files.Count;

            var i = 0;

            foreach (var file in files)
            {   
                var tmbName = file.FullName.Hash();
                var tmbPath = string.Format(@"{0}\{1}.png", Configuration.Configuration.TmbDir, tmbName);
                if (!System.IO.File.Exists(tmbPath))
                {
                    i++;
                    if (i > Configuration.Configuration.TmbsAtOnce)
                    {
                        response.tmb = true;
                        break;
                    }

                    ImageUtils.Resize(file.FullName, tmbPath, 50, 50, System.Drawing.Imaging.ImageFormat.Png, true);
                    images.Add(string.Format(imageFormatString, tmbName, string.Format("{0}/{1}.png", Configuration.Configuration.TmbUrl, tmbName)));
                }
            }

            if (images.Count > 0)
            {
                response.images = string.Format(@"{{{0}}}", string.Join(",", images.ToArray()));
            }

            return response;
        }

        #endregion
    }
}
